Skip to main content

同一页面三个组件请求同一个 API 发送了三次请求,如何优化

异步请求:用户数据

const fetchUser = (id) => {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Fetch: ", id);
resolve(id);
}, 1000);
});
};

思路:模拟缓存 cache 进行去重

  1. 声明 cache = {}
  2. 缓存 cache
    • 存在:直接返回缓存数据
    • 不存在:存入 cache 中,然后返回
const cache = {};
const cacheFetchUser = (id) => {
if (cache[id]) {
return cache[id];
}
cache[id] = fetchUser(id);
return cache[id];
};
cacheFetchUser(3).then((id) => console.log(id));
cacheFetchUser(3).then((id) => console.log(id));
cacheFetchUser(3).then((id) => console.log(id));

// 只会打印一次
// Fetch: 3